import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
// 引入路由规则
import routes from './routes'
/*import Mock from './mock'
Mock.bootstrap();*/
import 'font-awesome/css/font-awesome.min.css'

// 引入axios,因为后续我们需要通过axios调用后端接口
import axios from "axios"
// 在main.js中给axios配置一个全局的统一的前缀
//axios.defaults.baseURL = "/api"
// 因为由后端cors解决跨域,因此axios请求直接调用到后端接口即可
//axios.defaults.baseURL = "http://localhost:8081/"
//axios.defaults.baseURL = "http://api.car.com/"
axios.defaults.baseURL = "http://47.108.198.192:8888/"

Vue.prototype.$http = axios;  // 将axios交给vue,通过vue来进行使用

// 导入百度地图
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, {
  ak: 'QtL5wcGDYGRIdI5d8M8KBz1tAttKW7uB'
})

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//NProgress.configure({ showSpinner: false });

const router = new VueRouter({
  routes
})

// 是前端的登录拦截
router.beforeEach((to, from, next) => {
  if (to.path == '/login') {
    localStorage.removeItem('token');
    localStorage.removeItem('loginUser');
  }
  let user = JSON.parse(localStorage.getItem('loginUser'));
  if (!user && to.path != '/login') {
    next({ path: '/login' })
  } else {
    next()
  }
})

//router.afterEach(transition => {
//NProgress.done();
//});

// axios的前置拦截器  在访问到后端之前,会先经过这个拦截器,在这个拦截器里面,我们可以给每个请求都添加上一个请求头
axios.interceptors.request.use(config=>{
  let token = localStorage.getItem("token")
  if(token){
    config.headers["token"] = token;
  }
  return config;
},error => {
  Promise.reject(error)
})

// axios的后置拦截器  拦截到后端返回给前端的结果,先判断一下当前是不是因为未登录所返回的,如果是未登录,就要跳转回登录页面
axios.interceptors.response.use(config=>{
  console.log("========")
  let data = config.data;
  // == 只判断值不判断类型   === 既要判断值又要判断类型
  if(!data.success && (40015==data.code || 40016 == data.code)) {
    localStorage.removeItem("token");
    localStorage.removeItem("loginUser");
    router.push({ path: '/login' });
  }
  console.log("========")
  return config;
},error => {
  //Promise.reject(error)
})

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')

